package org.zwd.computePrice.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.zwd.computePrice.domain.User;

public class UserDao {
	public User findUserByid(int id){
		User user = null;
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try{
		conn = DBUtils.getConnection();
		String sql = "select id,username,phone,address,company from cp_user where id=?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setInt(1, id);
		rs = pstmt.executeQuery();
		
		if(rs.next()){
			user = new User();
			user.setId(rs.getInt(1));
			user.setUsername(rs.getString(2));
			user.setPhone(rs.getString(3));
			user.setAddress(rs.getString(4));
			user.setCompany(rs.getString(5));
		}
	} catch (SQLException e) {
		throw new RuntimeException(e);
	}
	finally {
		DBUtils.free(rs, pstmt, conn);
	}
	return user;
	}
	
	public void updateUserByid(User user){
		Connection conn = null;
		PreparedStatement pstmt = null;
		try{
		conn = DBUtils.getConnection();
		String sql = "update cp_user set username=?,phone=?,address=?,company=? where id=?";
		
		pstmt = conn.prepareStatement(sql);
		pstmt.setString(1, user.getUsername());
		pstmt.setString(2, user.getPhone());
		pstmt.setString(3, user.getAddress());
		pstmt.setString(4, user.getCompany());
		pstmt.setInt(5, user.getId());
		pstmt.executeUpdate();
		
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
		finally {
			DBUtils.free(null, pstmt, conn);
		}
	}
}
